# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings
from django.template import Context
from django.template.loader import get_template
from common.cache import redis_cache
from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.qr import make_code
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '10065': {  # 卓越支付 支付宝原生3.3% 100-3000 witch
        'API_KEY': 'rOqQblEAdJy7aCRzAJEzTmiJE5QffrNV',
        'gateway': 'https://zy.zypay.xyz/Index/api/pay.html',
        'query_gateway': 'https://zy.zypay.xyz/Index/api/query.html',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _get_create_agent_pay(mch_id):
    return APP_CONF[mch_id]['create_agent_pay']


def _get_query_agent_pay(mch_id):
    return APP_CONF[mch_id]['query_agent_pay']


def _get_query_balance(mch_id):
    return APP_CONF[mch_id]['query_balance']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k]:
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("zhuoyuepay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def _get_pay_type(service):
    if service == 'alipay_h5':
        return '102'
    elif service == 'alipay_scan':
        return '101'
    elif service == 'wechat_scan':
        return '103'
    elif service == 'unionpay':
        return '104'
    elif service == 'unionpay_h5':
        return '105'
    elif service == 'wechat_h5':
        return '106'
    return '102'


def _build_form(gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    # for k, v in params.items():
    #     html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>document.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)

    parameter_dict = OrderedDict((
        ('userid', app_id),
        ('innerorderid', str(pay.id)),
        ('money', str(pay_amount)),
        ('type', _get_pay_type(service)),
        ('notifyurl', '{}/pay/api/{}/zhuoyuepay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("zhuoyuepay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['innerorderid'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=3, verify=False)
    _LOGGER.info("zhuoyuepay create rsp: %s", response.text)
    data = json.loads(response.text)
    if str(data['type']) == '1':
        template_data = {'base64_img': make_code(data['data']), 'amount': pay_amount}
        t = get_template('qr_alipay_zhuoyue.html')
        html = t.render(Context(template_data))
        cache_id = redis_cache.save_html(pay.id, html)
        _LOGGER.info("zhuoyuepay create_url: %s, pay.id: %s", settings.PAY_CACHE_URL + cache_id, pay.id)
        return {'charge_info': settings.PAY_CACHE_URL + cache_id}
    elif str(data['type']) == '2':
        # <script>location.href='https:\/\/qr.alipay.com\/bax03156c9fyimnznggy60c3'<\/script>
        # 对这样的返回格式做提取
        # _LOGGER.info("data is: %s", data['data'].split("=")[1].split("<")[0].replace("'",""))
        if 'form' in data['data']:
            return {'charge_info': data['data']}
        else:
            return {'charge_info': data['data'].split("=")[1].split("<")[0].replace("'", "")}
    elif str(data['type']) == '3':
        # html_text = _build_form(data['data'])
        # cache_id = redis_cache.save_html(pay.id, html_text)
        # _LOGGER.info('zhuoyuepay url: %s', settings.PAY_CACHE_URL + cache_id)
        # return {'charge_info': settings.PAY_CACHE_URL + cache_id}
        return {'charge_info': data['data']}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("zhuoyuepay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['innerorderid']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('zhuoyuepay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['status'])
    trade_no = str(data['outorderid'])
    total_fee = float(data['money'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 2 支付成功;
    if trade_status == '2':
        _LOGGER.info('zhuoyuepay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('userid', app_id),
        ('innerorderid', str(pay_order.id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info('zhuoyuepay query data: %s, order_id is: %s', json.dumps(parameter_dict),
                 parameter_dict['innerorderid'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3, verify=False)
    _LOGGER.info('zhuoyuepay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['status'])
        total_fee = float(data['money'])
        trade_no = str(data['outorderid'])
        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }
        # 2 支付成功;
        if trade_status == '2':
            _LOGGER.info('zhuoyuepay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
